package com.leyou.gateway.filter;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.AppTokenScheduled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AppTokenScheduled appTokenScheduled;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request和response域
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //向请求头中添加当前微服务的token
        request.mutate().header(LyConstants.APP_TOKEN_HEADER, appTokenScheduled.getToken()).build();
        //获取当前请求url地址
        String url = request.getPath().toString(); //     /api/auth/login
        //判断当前url请求是否需要登录
        if(isWhite(url)){
            //继续执行其他过滤器链
            return chain.filter(exchange);
        }
        String token = null;
        Payload<UserInfo> payload = null;
        try {
            //获取token <cookieName <cookieName, cookieValue>>
            token = request.getCookies().getFirst(jwtProp.getCookie().getCookieName()).getValue();
            //解析token
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            //throw new LyException(ExceptionEnum.UNAUTHORIZED);
            //中止当前过滤器操作，并直接返回，不再经过其他过滤器了
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //判断当前token是否在黑名单
        String tokenId = payload.getId();
        if(redisTemplate.hasKey(tokenId)){
            //throw new LyException(ExceptionEnum.UNAUTHORIZED);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //获取用户id
        Long userId = payload.getUserInfo().getId();
        //向请求头中添加当前用户的id
        request.mutate().header(LyConstants.USER_HOLDER_KEY, userId.toString()).build();
        //继续执行其他过滤器链
        return chain.filter(exchange);
    }

    private boolean isWhite(String url) {
        for (String allowPath : filterProp.getAllowPaths()) {
            if(url.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
